package com.liu.notice.consumer;

import com.liu.notice.base.ServiceParent;
import com.liu.notice.mail.EmailSender;
import com.liu.notice.mail.Mail;
import com.liu.notice.utils.Dict;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author Liu Ke
 * @Date 2020/8/1  16:15
 * @Description	接收并处理邮件消息
 * @Version 1.0
 */
@Component
@Slf4j
public class MailReceiver extends ServiceParent {
	@Autowired
	private EmailSender emailSender;

	@RabbitListener(bindings = @QueueBinding(
			value = @Queue(value="${consumer.rabbitmq.queue}",durable = "${consumer.rabbitmq.queue.durable}"),
			exchange = @Exchange(name = "${consumer.rabbitmq.exchange}",
					durable = "${consumer.rabbitmq.exchange.durable}",
					type = "${consumer.rabbitmq.exchange.type}"),
			key = "${consumer.rabbitmq.key}"
	))
	@RabbitHandler
	public void emailHandler(@Payload Map<String,String> rabbitMqBody,
							 @Headers Map<String,Object> headers,
							 Channel channel) throws Exception {
		//收到消息，格式校验
		styleCheck(rabbitMqBody,Dict.SENDMAIL);
		//发送邮件
		Mail mail = new Mail();
		log.info("收到MQ消息并开始处理，用户名[{}]",rabbitMqBody.get(Dict.NAME));
		mail.setTo(rabbitMqBody.get(Dict.USEREMAIL));
		mail.setSubject(rabbitMqBody.get(Dict.SUBJECT));
		mail.setContent(rabbitMqBody.get(Dict.CONTENT));
		int i = emailSender.sendMail(mail);
		if(i==0){
			log.info("邮件发送成功，用户名[{}]",rabbitMqBody.get(Dict.NAME));
		}else{
			log.info("邮件发送失败，用户名[{}]",rabbitMqBody.get(Dict.NAME));
		}
		channel.basicAck((Long)headers.get(AmqpHeaders.DELIVERY_TAG),false);
	}
}
